package com.ytjj.qmyx.mall.controller;

import com.github.pagehelper.util.StringUtil;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.enums.ScoreSourceEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.DynamicConstant;
import com.ytjj.qmyx.mall.constants.IsAttentionConstant;
import com.ytjj.qmyx.mall.enums.BannerTypeEnums;
import com.ytjj.qmyx.mall.enums.DynamicCategoryEnums;
import com.ytjj.qmyx.mall.enums.DynamicEnum;
import com.ytjj.qmyx.mall.enums.DynamicOperationEnum;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.esmodel.LiveDto;
import com.ytjj.qmyx.mall.model.request.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.*;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.model.AddUserScoreRequest;
import com.ytjj.qmyx.users.model.ExpertDynamicDto;
import com.ytjj.qmyx.users.model.Label;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.ytjj.qmyx.mall.enums.DynamicCategoryEnums.*;


/**
 * 动态控制器
 *
 *
 * @version 1.0
 * 
 */
@RestController
@RequestMapping("/dynamic")
@Slf4j
public class DynamicController extends BaseController {

    private final DynamicService dynamicService;

    private final UsersClient usersClient;

    private final CommonService commonService;

    private final DynamicEvaluateInfoService dynamicEvaluateInfoService;

    private final LabelService labelService;


    public DynamicController(DynamicService dynamicService, UsersClient usersClient,
                             CommonService commonService,
                             DynamicCommentTypeService dynamicCommentTypeService,
                             DynamicEvaluateInfoService dynamicEvaluateInfoService,
                             LabelService labelService) {
        this.dynamicService = dynamicService;
        this.usersClient = usersClient;
        this.commonService = commonService;
        this.dynamicEvaluateInfoService = dynamicEvaluateInfoService;
        this.labelService = labelService;
    }

    /**
     * 获取动态测评的分类
     */
    @GetMapping("/getDynamicCategory")
    public CommonResult getDynamicCategory(){
        List<DynamicCategoryResponse> list = new ArrayList<>();
        DynamicCategoryEnums[] typeList = DynamicCategoryEnums.values();
        for (DynamicCategoryEnums type : typeList) {
            DynamicCategoryResponse atp = new DynamicCategoryResponse();
            atp.setNum(type.getNum());
            atp.setName(getNameByNum(type.getNum()));
            atp.setCode(getCodeByNum(type.getNum()));
            list.add(atp);
        }
        return CommonResult.success(list);
    }



    /**
     * 获取我的动态作品
     *
     * @return
     */
    @PostMapping("/getMyDynamic")
    private CommonResult getMyDynamic(@RequestBody PageRequest pageRequest) {
        UsersResponse usersResponse = this.getCurrentUser();
        MyDynamicResponse myDynamicResponse = new MyDynamicResponse();
        myDynamicResponse.setDynamicList(dynamicService.getDynamicListByUserId(usersResponse.getId(),
                pageRequest.getPageNum(),
                pageRequest.getPageSize()));
        myDynamicResponse.setBannerUrl(commonService.getSysConfigValue(SysConfigConstants.DYNAMIC_BANNER_URL));
        return CommonResult.success(myDynamicResponse);
    }

    /**
     * 获取我的动态作品详情
     *
     * @return
     */
    @PostMapping("/getMyDynamicInfos")
    private CommonResult getMyDynamicInfos(@RequestBody DynamicEsRequest dynamicEsRequest) {
        Integer ortherUsersId = null;
        if(dynamicEsRequest.getUserId() != null){
            ortherUsersId = dynamicEsRequest.getUserId();
        }
        List<DynamicResponse> dynamicEsResponseList = dynamicService.getMyDynamicInfos(dynamicEsRequest.getDynamicId(),
                this.getCurrentUser().getId(),
                ortherUsersId,
                dynamicEsRequest.getPageNum(),
                dynamicEsRequest.getPageSize());
        return CommonResult.success(dynamicEsResponseList);
    }

    /**
     * 获取动态页
     *
     * @return
     */
    @GetMapping("/getDynamicPage")
    private CommonResult getDynamicPage() {
        return CommonResult.success(dynamicService.getDynamicPage());
    }

    /**
     * 获取社区页
     *
     * @return
     */
    @GetMapping("/getCommunityPage")
    private CommonResult getCommunityPage() {
        CommunityPageResponse communityPage = dynamicService.getCommunityPage();
        UsersResponse usersResponse = getH5CurrentUser();
        if(null != usersResponse){
            if(!"17879311549".equals(usersResponse.getTel())){
                communityPage.setLive(null);
            }
        }else{
            communityPage.setLive(null);
        }
        return CommonResult.success(communityPage);
    }

    /**
     * 从es中获取动态信息
     *
     * @return
     */
    @PostMapping("/getEsDynamicList")
    private CommonResult getEsDynamicList(@RequestBody DynamicEsRequest dynamicEsRequest) {
        List<DynamicEsResponse> dynamicEsResponseList = null;
        if("h5".equals(TokenUtil.getRequest().getHeader("source"))) {
            dynamicEsResponseList = dynamicService.getEsDynamicList(dynamicEsRequest);
        }else{
            if(StringUtil.isEmpty(TokenUtil.getRequest().getHeader("token"))){
                dynamicEsResponseList = dynamicService.getEsDynamicList(dynamicEsRequest);
            }else{
                UsersResponse usersResponse = this.getH5CurrentUser();
                if(usersResponse == null){
                    dynamicEsResponseList = dynamicService.getEsDynamicList(dynamicEsRequest);
                }else{
                    dynamicEsResponseList = dynamicService.getEsDynamicList(dynamicEsRequest,usersResponse.getId());
                }
            }
        }
        return CommonResult.success(dynamicEsResponseList);
    }

    /**
     * 根据动态id/标签 获取明细信息列表
     *
     * @return
     */
    @PostMapping("/getEsDynamicInfos")
    private CommonResult getEsDynamicInfos(@RequestBody DynamicEsRequest dynamicEsRequest) {
        List<DynamicEsResponse> dynamicEsResponseList = null;
        if("h5".equals(TokenUtil.getRequest().getHeader("source"))) {
            dynamicEsResponseList = dynamicService.getEsDynamicInfos(dynamicEsRequest);
        }else{
            UsersResponse usersResponse = this.getH5CurrentUser();
            if(null == usersResponse){
                dynamicEsResponseList = dynamicService.getEsDynamicInfos(dynamicEsRequest);
            }else{
                dynamicEsResponseList = dynamicService.getEsDynamicInfos(dynamicEsRequest,usersResponse.getId());
            }
        }
        return CommonResult.success(dynamicEsResponseList);
    }


    /**
     * 根据专栏id获取动态列表
     * or
     * 根据类型获取动态列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getDynamicsBySpecialId")
    public CommonResult getDynamicListBySpecialId(@RequestBody DynamicRequest request) {
        if(StringUtil.isNotEmpty(request.getType())){
            return CommonResult.success(dynamicService.getDynamicsList(request.getType(),
                    request.getPageNum(),
                    request.getPageSize()));
        }else{
            return CommonResult.success(dynamicService.getDynamicListBySpecialId(request.getSpecialId(),
                    request.getPageNum(),
                    request.getPageSize()));
        }

    }

    /**
     * 根据用户id获取动态列表
     *
     * @param request
     * @return
     */
    @PostMapping("/getDynamicsByUserId")
    public CommonResult getDynamicsByUserId(@RequestBody DynamicRequest request) {
        return CommonResult.success(dynamicService.getDynamicListByUserId(request.getUserId(),
                request.getPageNum(),
                request.getPageSize()));
    }

    /**
     * 获取动态信息
     *
     * @return
     */
    @GetMapping("/getDynamicInfo")
    public CommonResult getDynamicInfo(@RequestParam("dynamicId") Integer dynamicId) {
        DynamicResponse response = dynamicService.getDynamicInfo(dynamicId);
        if (!DynamicConstant.SOURCE_H5.equals(getSource()) && !DynamicConstant.SOURCE_QA.equals(getSource())) {
            response.setIsAttention(StringUtil.isEmpty(TokenUtil.getRequest().getHeader("token")) ? IsAttentionConstant.NO :
                    usersClient.isAttention(getCurrentUser().getId(), response.getUserId()));
            response.setIsLike(dynamicService.isLike(response.getId(), getCurrentUser().getId()));
        }
        return CommonResult.success(response);
    }

    /**
     * 获取动态评论
     *
     * @param dynamicId
     * @return
     */
    @GetMapping("/getDynamicComment")
    public CommonResult getDynamicComment(@RequestParam("dynamicId") Integer dynamicId) {
        return CommonResult.success(dynamicService.getDynamicComment(dynamicId, 0));
    }

    /**
     * 点赞
     *
     * @param dynamicId
     * @return
     */
    @GetMapping("/like")
    public CommonResult like(@RequestParam("dynamicId") Integer dynamicId) {
        UsersResponse usersResponse = getCurrentUser();
        dynamicService.like(dynamicId, usersResponse.getId());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 取消点赞
     *
     * @param dynamicId
     * @return
     */
    @GetMapping("/cancelLike")
    public CommonResult cancelLike(@RequestParam("dynamicId") Integer dynamicId) {
        UsersResponse usersResponse = getCurrentUser();
        dynamicService.cancelLike(dynamicId, usersResponse.getId());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 点赞评论
     *
     * @return
     */
    @GetMapping("/likeComment")
    public CommonResult likeComment(@RequestParam("dynamicCommentId") Integer dynamicCommentId) {
        UsersResponse usersResponse = getCurrentUser();
        dynamicService.likeComment(dynamicCommentId, usersResponse.getId());
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 取消点赞评论
     *
     * @return
     */
    @GetMapping("/cancelLikeComment")
    public CommonResult cancelLikeComment(@RequestParam("dynamicCommentId") Integer dynamicCommentId) {
        UsersResponse usersResponse = getCurrentUser();
        dynamicService.cancelLikeComment(dynamicCommentId, usersResponse.getId());
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 评论
     *
     * @param request
     * @return
     */
    @PostMapping("/comment")
    public CommonResult comment(@RequestBody CommentRequest request) {
        request.setUserId(getCurrentUser().getId());
        int score = dynamicService.addComment(request);
        if ("APP".equals(TokenUtil.getPlatformData())) {
            AddDynamicCommentResponse response = new AddDynamicCommentResponse();
            response.setScore(score);
            response.setStarLevel(request.getStarLevel());
            return CommonResult.success(response);
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 评论  v2
     * @param request
     * @return
     */
    @PostMapping("/commentV2")
    public CommonResult commentV2(@RequestBody CommentRequest request) {
        request.setUserId(getCurrentUser().getId());
        DynamicCommentResponse data = dynamicService.addCommentV2(request, getCurrentUser());
        return CommonResult.success(data);
    }

    /**
     * 评星级
     * @param request
     * @return
     */
    @PostMapping("/evaluateStar")
    public CommonResult evaluteStar(@RequestBody CommentRequest request) {
        if (null == request.getFlag() || null == request.getStarLevel()) {
            throw new ApiException("评星和分类不能为空");
        }
        request.setUserId(getCurrentUser().getId());
        DynamicCommentResponse data = dynamicEvaluateInfoService.insert(request, getCurrentUser());
        return CommonResult.success(data);
    }

    /**
     * 专人动态
     *
     * @param expertId
     * @return
     */
    @GetMapping("/getExpertDynamicList")
    public CommonResult getExpertDynamicList(@RequestParam("expertId") Integer expertId) {
        return CommonResult.success(dynamicService.getExpertDynamicList(expertId));
    }

    /**
     * 获取动态中用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserDynamicInfo")
    public CommonResult getUserDynamicInfo(@RequestParam("userId") Integer userId) {
        return CommonResult.success(usersClient.getUsersInfo(userId));
    }

    /**
     * 获取他人动态列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/getOthersDynamicList")
    public CommonResult getOthersDynamicList(@RequestParam("userId") Integer userId,
                                            @RequestParam("pageSize") Integer pageSize,
                                             @RequestParam("pageNum") Integer pageNum) {
        return CommonResult.success(dynamicService.getOthersDynamicList(userId, pageSize,pageNum));
    }

    /**
     * 发布动态
     *
     * @param request
     * @return
     */
    @PostMapping("/issueDynamic")
    public CommonResult issueDynamic(@RequestBody IssueDynamicRequest request) {
        request.setUserId(getCurrentUser().getId());
        dynamicService.issueDynamic(request);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 获取H5动态列表
     *
     * @return
     */
    @GetMapping("/getH5DynamicList")
    public CommonResult getH5DynamicList() {
        H5DynamicResponse h5DynamicResponse = new H5DynamicResponse();
        List<ExpertDynamicDto> dynamicExpertList = usersClient.getDynamicExpertList();
        // 达人
        h5DynamicResponse.setExpertList(dynamicExpertList);
        // banner
        h5DynamicResponse.setBanners(dynamicService.getBannersInfoByType(BannerTypeEnums.DYNAMIC_LIVE.name()));
        return CommonResult.success(h5DynamicResponse);
    }

    @PostMapping("/getH5DynamicVideoList")
    public CommonResult getH5DynamicVideoList(@RequestBody DynamicRequest dynamicRequest) {
        if (DynamicEnum.RECOMMEND.name().equals(dynamicRequest.getType())) {
            dynamicRequest.setIsReason((byte) 1);
            List<DynamicResponse> h5DynamicVideoList = dynamicService.getH5DynamicVideoList(dynamicRequest);
            List<Object> resultList = new ArrayList<>();
            // 前端垃圾需求，请自行忽略这段垃圾代码
            if (dynamicRequest.getPageNum() <= 1) {
                resultList.add(this.getLiveDto().get(0));
                h5DynamicVideoList.stream()
                        .forEach(item -> resultList.add(item));
                return CommonResult.success(resultList);
            }
            // 第二页不带直播
            h5DynamicVideoList.stream()
                    .forEach(item -> resultList.add(item));
            return CommonResult.success(resultList);
        }
        if (DynamicEnum.VIDEO.name().equals(dynamicRequest.getType())) {
            dynamicRequest.setIsReason(null);
        }
        if (DynamicEnum.LIVE.name().equals(dynamicRequest.getType())) {
            return CommonResult.success(this.getLiveDto());
        }
        return CommonResult.success(dynamicService.getH5DynamicVideoList(dynamicRequest));
    }

    @GetMapping("/getH5ExpertInfoById")
    public CommonResult getH5ExpertInfoById(@RequestParam("userId") Integer userId) {
        return CommonResult.success(dynamicService.getH5ExpertInfoById(userId));
    }

    /**
     * 统计动态浏览记录
     * @param browsingHistoryRequest
     * @return
     */
    @PostMapping("/saveBrowsingHistory")
    public CommonResult saveBrowsingHistory(@RequestBody BrowsingHistoryRequest browsingHistoryRequest ) {
        if(null == this.getH5CurrentUser() || this.getH5CurrentUser().getId() == null){
            return CommonResult.success();
        }
        dynamicService.saveBrowsingHistory(browsingHistoryRequest, this.getH5CurrentUser().getId(), DynamicOperationEnum.DYNAMIC.name());
        return CommonResult.success();
    }

    @PostMapping("/addBrowsingScore")
    public CommonResult addBrowsingScore(@RequestBody BrowsingHistoryRequest request) {
        if(null == this.getH5CurrentUser() || this.getH5CurrentUser().getId() == null){
            return CommonResult.success();
        }
        return CommonResult.success(usersClient.addScore(new AddUserScoreRequest(this.getH5CurrentUser().getId(), ScoreSourceEnum.BROWSE_VIDEO, request.getDynamicId())));
    }

    /**
     * 分享视频记录
     * @return
     */
    @PostMapping("/saveShareHistory")
    public CommonResult saveShareHistory(@RequestBody BrowsingHistoryRequest request) {
        if(null == this.getH5CurrentUser() || this.getH5CurrentUser().getId() == null){
            return CommonResult.success();
        }
        return CommonResult.success(usersClient.addScore(new AddUserScoreRequest(this.getH5CurrentUser().getId(), ScoreSourceEnum.SHARE_VIDEO, request.getDynamicId())));
    }

    /**
     * @Description 发布购物清单动态
     *
     *
     * 
     * @Version 1.0
     **/
    @PostMapping("/publishShippingDynamic")
    public CommonResult publishOrderDynamic(@RequestBody ShippingDynamicRequest shippingDynamicRequest) {
        UsersResponse currentUser = getCurrentUser();
        shippingDynamicRequest.setUserId(currentUser.getId());
        return CommonResult.success(dynamicService.publishShippingDynamic(shippingDynamicRequest, currentUser));
    }


    /**
     * 直播dto获取
     */
    public List<LiveDto> getLiveDto() {
        List<Product> liveProductList = dynamicService.getLiveProductList();
        List<LiveDto> liveDtoList = new ArrayList<>();
        LiveDto liveDto = new LiveDto()
                .setImg("http://img.XXXX.com/service/eedc5dbfc36b476aa5e27d55ddbf0567.jpg")
                .setPriseNum(3258)
                .setTitle("神秘好货免费领，美女配名表是兄弟就来直播间等你。")
                .setHeadImg("http://img.XXXX.com/service/eedc5dbfc36b476aa5e27d55ddbf0567.jpg")
                .setUserName("XXXX优品官")
                .setType("live")
                .setLiveStatus(0)
                .setHideNum(liveProductList.size() - 3)
                .setProductList(liveProductList);
        liveDtoList.add(liveDto);
        return liveDtoList;
    }

    @GetMapping("/getDynamicById")
    public DynamicDto getDynamicById(@RequestParam("dynamicId") Integer dynamicId){
        return dynamicService.getDynamicById(dynamicId);
    }

    @GetMapping("/getDynamicCountByUserId")
    public DynamicDto getDynamicCountByUserId(@RequestParam("userId") Integer userId, @RequestParam(value = "status",required = false) Integer status) {
        DynamicDto dto = new DynamicDto();
        dto.setNum(dynamicService.getDynamicCountByUserId(userId, status));
        return dto;
    }

    /**
     * 获取评论分类列表
     * @return
     */
    @GetMapping("/commentType")
    public CommonResult getDynamicCommentType() {
        List<Label> list = labelService.queryAll();
        List<DynamicCommentType> types = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(item -> {
                DynamicCommentType type = new DynamicCommentType();
                type.setId(item.getId());
                type.setName(item.getTitle());
                types.add(type);
            });
        }
        DynamicCommentTypeResponse response = new DynamicCommentTypeResponse();
        response.setTypes(types);
        return CommonResult.success(response);
    }

    /**
     * 获取所有关注达人的测评数
     * @return
     */
    @PostMapping("/dynamicUnReadNum")
    public CommonResult getDynamicUnreadNum() {
        DynamicUnReadNumResponse response = new DynamicUnReadNumResponse();
        response.setNum(0);
        try {
            UsersResponse currentUser = getCurrentUser();
            if (null != currentUser) {
                Integer num = dynamicService.talentDynamicNum(currentUser.getId());
                if (null != num && num > 0) {
                    response.setNum(num);
                }
            }
        } catch (Exception e) {
            log.error("===未登录");
        }
        return CommonResult.success(response);
    }

    /**
     * 获取专区下的商品测评列表（多级专区）
     *
     * @param specialId
     * @return
     */
    @GetMapping("/getDynamicInfoBySpecialId")
    public CommonResult getDynamicInfoBySpecialId(@RequestParam("specialId") Integer specialId) {
        return CommonResult.success(dynamicService.getDynamicBySpecialId(specialId));
    }

    /**
    * 获取动态评论列表
    * v4.2.2
    * @param dynamicCommentRequest
    * @returns: com.ytjj.common.api.CommonResult
    * 
    */
    @PostMapping("/getDynamicComments")
    public CommonResult getDynamicComments(@RequestBody DynamicCommentRequest dynamicCommentRequest) {
        return CommonResult.success(dynamicService.getDynamicComments(dynamicCommentRequest));

    }

    /**
     * 获取评论的回复列表
     * v4.2.2
     * @param dynamicCommentReplyRequest
     * @returns: com.ytjj.common.api.CommonResult
     * 
     */
    @PostMapping("/getDynamicCommentsReply")
    public CommonResult getDynamicCommentsReply(@RequestBody DynamicCommentReplyRequest dynamicCommentReplyRequest) {
        return CommonResult.success(dynamicService.getDynamicCommentReplys(dynamicCommentReplyRequest));
    }

    /**
     * 添加评论
     * v4.2.2
     * @return
     */
    @PostMapping("/addCommentForDynamic")
    public CommonResult addCommentForDynamic(@RequestBody DynamicCommentRequest dynamicCommentRequest) {
        return CommonResult.success(dynamicService.addCommentForDynamic(dynamicCommentRequest));
    }

    /**
     * 添加回复
     * v4.2.2
     * @return
     */
    @PostMapping("/addCommentReply")
    public CommonResult addCommentReply(@RequestBody DynamicCommentReplyRequest dynamicCommentReplyRequest) {
        return CommonResult.success(dynamicService.addCommentReply(dynamicCommentReplyRequest));
    }

    /**
     * 评论点赞
     * v4.2.2
     * @return
     */
    @GetMapping("/clickLike")
    public CommonResult clickLike(Integer type, Integer id, Integer userId, Integer dynamicId) {
        return CommonResult.success(dynamicService.clickLike(type,id,userId,dynamicId));
    }

    /**
     * 相关测评推荐
     * v4.2.2
     * @return
     */
    @GetMapping("/relatedDynamicRecommend")
    public CommonResult relatedDynamicRecommend(Integer dynamicId) {
        return CommonResult.success(dynamicService.relatedDynamicRecommend(dynamicId));
    }

}
